package com.pascuit.gpxhandler.server.controller;

import java.io.IOException;
import java.util.Date;
import java.util.GregorianCalendar;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.datatype.DatatypeConfigurationException;
import javax.xml.datatype.DatatypeFactory;
import javax.xml.datatype.XMLGregorianCalendar;

import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.google.appengine.api.blobstore.BlobKey;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import com.pascuit.gpxhandler.server.service.GpxServiceImpl;
import com.pascuit.gpxhandler.shared.generated.jaxb2.Gpx;

/**
 * 
 * @author Parant
 * 
 */
public class GpxServlet extends RemoteServiceServlet {

	private static final long serialVersionUID = 1L;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String startTime = req.getParameter("startTime");
		String endTime = req.getParameter("endTime");
		String synchronize = req.getParameter("synchronize");

		boolean needSynchro = Boolean.valueOf(synchronize);

		BlobKey blobKey = new BlobKey(req.getParameter("blob-key"));
		WebApplicationContext applicationContext = WebApplicationContextUtils
				.getWebApplicationContext(getServletContext());

		GpxServiceImpl gpxService = (GpxServiceImpl) applicationContext.getBean("gpxService");
		Gpx gpx = gpxService.loadGpxWithJaxb2(blobKey);

		if (needSynchro && gpx.getMetadata() != null) {
			Date gpsStartDate = gpxService.getGpsStartDate(gpx.getTrks());

			GregorianCalendar gregorianCalendar = gpx.getMetadata().getTime().toGregorianCalendar();
			gregorianCalendar.setTime(gpsStartDate);

			try {
				XMLGregorianCalendar xgcal = DatatypeFactory.newInstance().newXMLGregorianCalendar(gregorianCalendar);
				gpx.getMetadata().setTime(xgcal);
			} catch (DatatypeConfigurationException e) {
				throw new RuntimeException(e.getMessage(), e);
			}
		}

		gpxService.cutFile(gpx, Long.valueOf(startTime), Long.valueOf(endTime));

		resp.addHeader("Content-type", "application/force-download");
		resp.addHeader("Content-Disposition", "filename=modifiedGpx.gpx");
		gpxService.convertFromObjectToXMLWithJaxb2(gpx, resp.getOutputStream());
	}
}
